import { defineStore } from "pinia";
import type { UserInfo, NavModeType, LanguageType } from "@/types";
import {
  login,
  register,
  getUserInfo,
  logout,
  getProfile,
  editProfile,
} from "@/api/user";
import { ElMessage } from "element-plus";

interface UserState {
  token: string | null;
  userInfo: Partial<UserInfo>;
}

export const useUserStore = defineStore("user", {
  state: (): UserState => ({
    token: null,
    userInfo: {
      language: "zh",
      navigation: "side",
    },
  }),

  actions: {
    setToken(token: string) {
      this.token = token;
    },
    reset() {
      Object.assign(this, {
        token: null,
        userInfo: {},
      });
    },
    setLanguage(lang: LanguageType) {
      Object.assign(this.userInfo, {
        language: lang,
      });
    },
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo;
    },
    setNavMode(mode: NavModeType) {
      Object.assign(this.userInfo, {
        navigation: mode,
      });
    },
    logout(): void {
      this.reset();
    },
    // 登录
    async loginAction(username: string, password: string) {
      try {
        const res = await login({ username, password });
        if (res.data.access_token) {
          this.setToken(res.data.access_token);
          const res2 = await getProfile();
          this.setUserInfo(res2.data);
        }
        return res;
      } catch (error) {
        console.error("登录失败:", error);
        throw error;
      }
    },
    // 保存设置
    async saveUserInfoAction(info?: Partial<UserInfo>) {
      try {
        const { id, createdAt, updatedAt, password, ...user } = this.userInfo;
        if (!id) return ElMessage.error("请先登录");
        const res = await editProfile(id, { ...user, ...info });
        return res;
      } catch (error) {
        console.error("保存设置失败:", error);
        throw error;
      }
    },
    // 注册
    async registerAction(data: {
      username: string;
      email: string;
      password: string;
      confirmPassword: string;
    }) {
      try {
        const res = await register(data);
        return res;
      } catch (error) {
        console.error("注册失败:", error);
        throw error;
      }
    },

    // 获取用户信息
    async getUserInfoAction() {
      try {
        const res = await getUserInfo();
        this.userInfo = res.data;
        return res;
      } catch (error) {
        console.error("获取用户信息失败:", error);
        throw error;
      }
    },

    // 登出
    async logoutAction() {
      try {
        await logout();
        this.token = "";
        this.userInfo = {};
      } catch (error) {
        console.error("登出失败:", error);
        throw error;
      }
    },
  },
  // 开启数据缓存
  persist: {
    storage: sessionStorage,
  },
});
